package com.turbo.cloud.calc.lottery;

import java.util.HashMap;
import java.util.Map;

public class LotteryPrediction {
    // 状态转移概率矩阵
    private Map<Integer, Map<Integer, Double>> transitionMatrix = new HashMap<>();
    // 状态数量
    private int stateNum;

    /**
     * 构造函数
     * @param stateNum 状态数量
     */
    public LotteryPrediction(int stateNum) {
        this.stateNum = stateNum;
    }

    /**
     * 添加历史开奖记录
     * @param history 历史开奖记录
     */
    public void addHistory(int[] history) {
        if (history == null || history.length == 0) {
            return;
        }
        int prev = history[0];
        for (int i = 1; i < history.length; i++) {
            int curr = history[i];
            Map<Integer, Double> map = transitionMatrix.getOrDefault(prev, new HashMap<>());
            double prob = map.getOrDefault(curr, 0.0);
            map.put(curr, prob + 1.0);
            transitionMatrix.put(prev, map);
            prev = curr;
        }
    }

    /**
     * 预测下一期的开奖号码
     * @param curr 当前期开奖号码
     * @param topN 预测的前N个号码
     * @return 预测的开奖号码
     */
    public int[] predict(int[] curr, int topN) {
        if (curr == null || curr.length == 0) {
            return new int[0];
        }
        int[] result = new int[topN];
        double[] prob = new double[stateNum];
        for (int i = 0; i < stateNum; i++) {
            double p = transitionMatrix.getOrDefault(curr[curr.length - 1], new HashMap<>()).getOrDefault(i + 1, 0.0);
            prob[i] = p;
        }
        for (int i = 0; i < topN; i++) {
            int maxIndex = 0;
            for (int j = 0; j < stateNum; j++) {
                if (prob[j] > prob[maxIndex]) {
                    maxIndex = j;
                }
            }
            result[i] = maxIndex + 1;
            prob[maxIndex] = -1;
        }
        return result;
    }
}
